package pl.kosmowska.ewelina.client.views.impl;

import java.util.Date;

import pl.kosmowska.ewelina.client.ViewMessages;
import pl.kosmowska.ewelina.client.app.requestfactory.dto.InvestmentDataProxy;
import pl.kosmowska.ewelina.client.views.InvestmentEditView;
import pl.kosmowska.ewelina.client.views.widgets.MessageDialogBox;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DoubleBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.IntegerBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ResizeLayoutPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.visualizations.PieChart;
import com.google.gwt.visualization.client.visualizations.PieChart.Options;

public class InvestmentEditViewImpl extends Composite implements InvestmentEditView{

	private static InvestmentEditViewImplUiBinder uiBinder = GWT
			.create(InvestmentEditViewImplUiBinder.class);
	@UiField Button confirmButton;
	@UiField Button clearButton;
	@UiField HorizontalPanel datePanel;
	@UiField Label warningLabel;
	@UiField TextBox nameBox;
	@UiField DoubleBox valueBox;
	@UiField DoubleBox percentageBox;
	@UiField ListBox installmentChoiceBox;
	@UiField IntegerBox monthNumberBox;
	@UiField VerticalPanel summaryPanel;
	@UiField Label clientCapitalLabel;
	@UiField Label investmentCapitalLabel;
	@UiField Label taxLabel;
	@UiField Label interestsLabel;
	@UiField ResizeLayoutPanel chartPanel;
	@UiField HorizontalPanel bottomButtonPanel;

	DateBox startDateBox;

	private Presenter presenter;
	private boolean alreadyInit;
	private InvestmentDataProxy investmentData;
	private String name;
	private float value;
	private float percentage;
	private Date startDate;
	private int installmentChoice;
	private Integer monthNumber;
	private float clientCapital;
	private float finalCapital;
	private Date endDate;


	interface InvestmentEditViewImplUiBinder extends UiBinder<Widget, InvestmentEditViewImpl> {
	}

	public InvestmentEditViewImpl() {
		initWidget(uiBinder.createAndBindUi(this));
		datePanel.add(initStartDateBox());
		initInstallmentChoiceBox();
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public void reInitView() {
		summaryPanel.setVisible(false);
		bottomButtonPanel.setVisible(false);
		if(investmentData!=null){
			fillForm();
		}else{
			clearForm();
		}
	}

	private void clearForm() {
		nameBox.setText(null);
		valueBox.setValue(null);
		percentageBox.setValue(null);
		startDateBox.setValue(null);
		monthNumberBox.setValue(null);
	}

	private void initInstallmentChoiceBox() {
		installmentChoiceBox.addItem("Kapitalizacja miesięczna");
		installmentChoiceBox.addItem("Kapitalizacja kwartalna");
		installmentChoiceBox.addItem("Kapitalizacja roczna");
	}


	public void setData(InvestmentDataProxy InvestmentData) {
		this.investmentData = InvestmentData;
	}

	private void fillForm() {
		nameBox.setText(investmentData.getName());
		valueBox.setValue((double)investmentData.getValue());
		percentageBox.setValue((double)investmentData.getPercentage());
		startDateBox.setValue(investmentData.getStartDate());
		installmentChoiceBox.setSelectedIndex(investmentData.getInstallmentChoice());
		monthNumberBox.setValue(investmentData.getMonthNumber());
	}

	public HorizontalPanel initStartDateBox(){
		// Create a DateBox
		DateTimeFormat dateFormat = DateTimeFormat.getLongDateFormat();
		startDateBox = new DateBox();
		startDateBox.setFormat(new DateBox.DefaultFormat(dateFormat));

		// Combine the widgets into a panel and return them
		HorizontalPanel vPanel = new HorizontalPanel();
		vPanel.add(new HTML("Data rozpoczęcia: "));
		vPanel.add(startDateBox);
		return vPanel;
	}


	@UiHandler("clearButton")
	void onClearButtonClick(ClickEvent event) {
		clearForm();
	}
	@UiHandler("returnButton")
	void onReturnButtonClick(ClickEvent event) {
		presenter.goToInvestmentPlace();
	}
	@UiHandler("calculateButton")
	void onCalculateButtonClick(ClickEvent event) {
		if(validateForm()){
			name = nameBox.getText();
			value = valueBox.getValue().floatValue();
			percentage = percentageBox.getValue().floatValue();
			startDate = startDateBox.getValue();
			installmentChoice = installmentChoiceBox.getSelectedIndex();
			monthNumber = monthNumberBox.getValue();

			presenter.calculateInvestment(name, value, percentage, startDate, installmentChoice, monthNumber);

		}else{
			showMessage(ViewMessages.ERROR_WRONG_INPUT);
		}

	}

	private boolean validateForm() {
		if(validate(startDateBox)&& validate(nameBox)&& validate(percentageBox)&& validate(monthNumberBox)){
			return true;
		}else{
			return false;
		}
	}

	private boolean validate(IntegerBox integerBox) {
		if(integerBox.getValue()==null)
			return false;
		else
			return true;
	}

	private boolean validate(DateBox dateBox) {
		if(dateBox.getValue()==null)
			return false;
		else
			return true;
	}

	private boolean validate(DoubleBox doubleBox) {
		if(doubleBox.getValue()==null)
			return false;
		else
			return true;
	}

	private boolean validate(TextBox textbox) {
		if(textbox.getText()==null || textbox.getText().equals("") )
			return false;
		else
			return true;
	}
	@Override
	public void loadChart(final AbstractDataTable dataTable){
		PieChart pie = new PieChart(dataTable, createOptions());
		chartPanel.setWidget(pie);
		bottomButtonPanel.setVisible(true);
	}


	private Options createOptions() {
		Options options = Options.create();
		options.setWidth(400);
		options.setHeight(240);
		options.set3D(true);
		options.setTitle("Wykres lokaty");
		return options;
	}

	@Override
	public void showSummary(float clientCapital, float finalCapital, float intrestAmount, float tax, Date endDate) {
		this.clientCapital = clientCapital;
		this.finalCapital = finalCapital;
		this.endDate = endDate;
		summaryPanel.setVisible(true);
		clientCapitalLabel.setText(String.valueOf(round(clientCapital)));
		investmentCapitalLabel.setText(String.valueOf(round(finalCapital)));
		interestsLabel.setText(String.valueOf(round(intrestAmount)));
		taxLabel.setText(String.valueOf(round(tax)));
	}

	@UiHandler("confirmButton")
	void onConfirmButtonClick(ClickEvent event) {	    
		presenter.saveInvestmentData(name, clientCapital,finalCapital, monthNumber, percentage, installmentChoice, startDate, endDate);
	}

	private double round (double val)
	{
		double exp = Math.pow(10, 2);
		double rounded = val * exp;
		rounded = Math.round(rounded);
		return rounded / exp;
	}

	
	@Override
	public void showMessage(String errorMessage) {
		MessageDialogBox messageDialogBox = new MessageDialogBox(errorMessage);
		messageDialogBox.center();
		messageDialogBox.show();

	}
	@Override
	public boolean isAlreadyInit() {
		return alreadyInit;
	}
	@Override
	public void setAlreadyInit(boolean alreadyInit) {
		this.alreadyInit = alreadyInit;
	}




}
